<template>
  <n-card :bordered="false">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
  </n-card>
  <n-card :bordered="false" class="mt-3">
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row:ArticleItem) => row.articleID"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
      :striped="true"
      :pagination="{
        pageSize: 10,
        showSizePicker: true,
        pageSizes: [10, 20, 30, 50],
        onChange: (page) => {
          console.log(page);
        },
        onUpdatePageSize: (pageSize) => {
          console.log(pageSize);
        }
      }"
    >
      <template #tableTitle>
        <n-space>
          <n-button type="primary" @click="handleRefresh">
            <template #icon>
              <n-icon>
                <ReloadOutlined />
              </n-icon>
            </template>
            刷新
          </n-button>
        </n-space>
      </template>

      <template #toolbar> </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="名称" path="name">
          <n-input placeholder="请输入名称" v-model:value="formParams.name" />
        </n-form-item>
        <n-form-item label="地址" path="address">
          <n-input type="textarea" placeholder="请输入地址" v-model:value="formParams.address" />
        </n-form-item>
        <n-form-item label="日期" path="date">
          <n-date-picker type="datetime" placeholder="请选择日期" v-model:value="formParams.date" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { columns, ArticleItem } from './columns';
import { PlusOutlined, ReloadOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { type FormRules } from 'naive-ui';
import { ArticleApi } from "@/api/ArticleApi";
import { AdminManagementApi } from '@/api/new/AdminManagementApi';
import { useMessage } from 'naive-ui';

const rules: FormRules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入名称',
  },
  address: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入地址',
  },
  date: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择日期',
  },
};

const router = useRouter();
const formRef: any = ref(null);
const actionRef = ref();
const message = useMessage();

const showModal = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  name: '',
  address: '',
  date: null,
});

// 表单配置
const schemas: FormSchema[] = [
  {
    field: 'title',
    component: 'NInput',
    label: '文章标题',
    componentProps: {
      placeholder: '请输入文章标题',
    },
  },
  {
    field: 'authorID',
    component: 'NInputNumber',
    label: '作者ID',
    componentProps: {
      placeholder: '请输入作者ID',
      showButton: false,
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '草稿',
          value: 'draft',
        },
        {
          label: '已发布',
          value: 'published',
        },
        {
          label: '待审核',
          value: 'pendingReview',
        },
        {
          label: '已删除',
          value: 'deleted',
        },
      ],
    },
  },
];

const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

// 操作列定义
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '查看',
          onClick: handleView.bind(null, record),
        },
        {
          label: '发布',
          onClick: handlePublish.bind(null, record),
          ifShow: () => record.status !== 'published' && record.status !== 'deleted',
          type: 'success',
        },
        {
          label: '打回草稿',
          onClick: handleDraft.bind(null, record),
          ifShow: () => record.status !== 'draft' && record.status !== 'deleted',
          type: 'warning',
        },
      ],
    });
  },
});

// 加载表格数据（实现前端分页）
const loadDataTable = async (res) => {
  try {
    // 获取所有文章
    const response = await ArticleApi.getAllArticles();
    
    // 过滤条件
    const { title, authorID, status } = getFieldsValue();
    let filteredData = response;
    
    if (title) {
      filteredData = filteredData.filter(item => 
        item.title.toLowerCase().includes(title.toLowerCase())
      );
    }
    
    if (authorID) {
      filteredData = filteredData.filter(item => 
        item.authorID === authorID
      );
    }
    
    if (status) {
      filteredData = filteredData.filter(item => 
        item.status === status
      );
    }
    
    // 计算分页数据
    const { page = 1, pageSize = 10 } = res;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pagedData = filteredData.slice(startIndex, endIndex);
    
    return {
      list: pagedData,
      page: page,
      pageSize: pageSize,
      pageCount: Math.ceil(filteredData.length / pageSize),
      itemCount: filteredData.length,
    };
  } catch (error) {
    message.error('获取文章列表失败');
    return {
      list: [],
      page: 1,
      pageSize: 10,
      pageCount: 0,
      itemCount: 0,
    };
  }
};

function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}

function handleRefresh() {
  actionRef.value.reload();
  message.success('刷新成功');
}

// 查看文章详情
function handleView(record: ArticleItem) {
  router.push({
    name: 'article_detail',
    params: {
      id: record.articleID
    }
  });
}

// 发布文章
async function handlePublish(record: ArticleItem) {
  try {
    await AdminManagementApi.publishArticle(record.articleID);
    message.success('文章已发布');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

// 设置为草稿
async function handleDraft(record: ArticleItem) {
  try {
    await AdminManagementApi.draftArticle(record.articleID);
    message.success('文章已设置为草稿');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

function confirmForm(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      window['$message'].success('新建成功');
      setTimeout(() => {
        showModal.value = false;
        actionRef.value.reload();
      });
    } else {
      window['$message'].error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function handleSubmit(values: Recordable) {
  console.log(values);
  actionRef.value.reload();
}

function handleReset(values: Recordable) {
  console.log(values);
  actionRef.value.reload();
}
</script>

<style lang="less" scoped></style>
